<?php
/*
 * @Description    : 电子合同类
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2020-10-29 15:53:35
 * @LastEditors    : QianLong
 * @LastEditTime   : 2024-03-30 16:28:50
 */

namespace app\common\service;

use app\lib\exception\ApiException;
use Yurun\Util\HttpRequest;
use AlibabaCloud\Credentials\Credential;
use AlibabaCloud\SDK\Cloudauth\V20190307\Cloudauth;
use AlibabaCloud\SDK\Cloudauth\V20190307\Models\Id2MetaVerifyRequest;
use AlibabaCloud\SDK\Cloudauth\V20190307\Models\Id2MetaVerifyResponse;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Cloudauth\V20221125\Cloudauth as CloudauthV2;
use \Exception;
use think\facade\Db;
use AlibabaCloud\SDK\Cloudauth\V20221125\Models\EntElementVerifyRequest;

class Contract
{
    // 企业四要素校验
    // https://market.aliyun.com/products/56928005/cmapi00062634.html?spm=5176.2020520132.101.12.21bf72187mY70T#sku=yuncode56634000015
    // https://help.aliyun.com/zh/id-verification/enterprise-identity-authentication/product-overview/product-introduction-1?spm=a2c4g.11186623.0.0.513d768f1IXM3A
    public static function companyFourCheck($company, $company_no, $person, $idcard, $contract_id)
    {
        $hasCom = Db::connect('mongodb')->name('com_verify_check')->where('com_no', md5(trim($company_no)))->find();
        if (!empty($hasCom)) {
            if ($hasCom['com_no'] != md5(trim($company_no))) {
                throw new ApiException('[L]企业验证失败-营业执照号不一致');
            }
            if ($hasCom['person'] != md5(trim($person))) {
                throw new ApiException('[L]企业验证失败-法人名称不一致');
            }
            if ($hasCom['idcard'] != md5(trim($idcard))) {
                throw new ApiException('[L]企业验证失败-法人证件号码不一致');
            }
            $return['orderNo'] = 'LOCAL' . $hasCom['_id'];
            return $return;
        }
        if (empty($contract_id)) {
            $contract_id = createId();
        }
        $client = self::createClientV2();
        $entElementVerifyRequest = new EntElementVerifyRequest([
            "infoVerifyType" => "ENT_4META",
            "merchantBizId" => createId(),
            "licenseNo" => $company_no,
            "entName" => $company,
            "legalPersonCertNo" => $idcard,
            "legalPersonName" => $person,
            "sceneCode" => "1000000001",
            "userAuthorization" => "1",
            "merchantUserId" => $contract_id
        ]);
        $runtime = new RuntimeOptions([]);
        // 复制代码运行请自行打印 API 的返回值
        $result = $client->entElementVerifyWithOptions($entElementVerifyRequest, $runtime);
        $result = json_decode(json_encode($result), true);
        if ($result['statusCode'] != 200) {
            throw new ApiException('企业验证失败-验证请求异常');
        }
        if (strtolower($result['body']['code']) != 'success') {
            throw new ApiException('企业验证失败-' . $result['body']['message']);
        }
        $return['orderNo'] = json_encode($result['body']);
        $detailReason['LegalPersonNameFlag'] = '法人名称不一致';
        $detailReason['LegalPersonCertNoFlag'] = '法人证件号码不一致';
        $detailReason['EntNameFlag'] = '企业名称不一致';
        $detailReason['LicenseNoFlag'] = '营业执照号不一致';
        if ($result['body']['result']['bizCode'] != '1' && $result['body']['result']['bizCode'] != 1) {
            if (isset($result['body']['result']['reasonDetail']) && !empty($result['body']['result']['reasonDetail'])) {
                $detailArr = explode(',', $result['body']['result']['reasonDetail']);
                $detailStr = [];
                foreach ($detailArr as $vo) {
                    if (isset($detailReason[$vo])) {
                        $detailStr[] = $detailReason[$vo];
                    }
                }
                if (!empty($detailStr)) {
                    throw new ApiException('企业验证失败-' . implode(',', $detailStr));
                }
            }else{
                $postData['lsi_id'] = 'LSI4928884355241870';
                $postData['result'] = json_encode($result);
                $postData['type'] = '企业验证';
                $postData['time'] = time();
                doLogPush($postData);
                throw new ApiException('企业验证失败-未知原因');
            }
        }
        $insert['_id'] = createId();
        $insert['com_name'] = md5(trim($company));
        $insert['com_no'] = md5(trim($company_no));
        $insert['person'] = md5(trim($person));
        $insert['idcard'] = md5(trim($idcard));
        Db::connect('mongodb')->name('com_verify_check')->insert($insert);
        return $return;
    }
    // public static function companyFourCheck($company, $company_no, $person, $idcard)
    // {
    //     $url = 'https://slyqys.market.alicloudapi.com/company-four/check';
    //     $data['companyName'] = $company;
    //     $data['creditNo'] = $company_no;
    //     $data['legalPerson'] = $person;
    //     $data['idCard'] = $idcard;
    //     $header = ['Authorization' => 'APPCODE 08b451d6c29548b0a103147c131eb6e4'];
    //     $http = new HttpRequest;
    //     $result = $http->headers($header)->get($url . '?' . http_build_query($data));
    //     $resultBody = json_decode($result->body(), true);
    //     if ($resultBody['code'] != 200) {
    //         throw new ApiException('企业验证失败-' . $resultBody['msg']);
    //     }
    //     $return['orderNo'] = $resultBody['data']['orderNo'];
    //     if ($resultBody['data']['companyName'] != true) {
    //         throw new ApiException('企业验证失败-公司信息错误');
    //     }
    //     if ($resultBody['data']['creditNo'] != true) {
    //         throw new ApiException('企业验证失败-公司信息错误');
    //     }
    //     if ($resultBody['data']['legalPerson'] != true) {
    //         throw new ApiException('企业验证失败-法人信息错误');
    //     }
    //     if ($resultBody['data']['idCard'] != true) {
    //         throw new ApiException('企业验证失败-法人信息错误');
    //     }
    //     return $return;
    // }
    public static function createClientV2()
    {
        $akInfo = getAk('AK4908977824885837');
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $akInfo['aliyun_key_id'],
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $akInfo['aliyun_key_secret']
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Cloudauth
        $config->endpoint = "cloudauth.aliyuncs.com";
        return new CloudauthV2($config);
    }
    public static function createClient(string $endpoint): Cloudauth
    {
        $akInfo = getAk('AK4908977824885837');
        $credential = new Credential([
            'access_key_id'     => $akInfo['aliyun_key_id'],
            'access_key_secret' => $akInfo['aliyun_key_secret'],
        ]);
        $config = new Config([
            // 使用credential配置凭证
            "credential" => $credential,
            "endpoint" => $endpoint

        ]);
        return new Cloudauth($config);
    }
    // 身份认证（二要素）
    // https://market.aliyun.com/products/57000002/cmapi029847.html?spm=5176.2020520132.101.4.21bf72187mY70T
    public static function username2Meta($person, $idcard)
    {
        $request = new Id2MetaVerifyRequest([
            "ParamType" => "normal",
            "UserName" => $person,
            "IdentifyNum" => $idcard,

        ]);
        // 推荐，支持服务路由。
        $response = self::id2MetaVerifyAutoRoute($request);
        var_dump($response->body->requestId);
        var_dump($response->body->code);
        var_dump($response->body->message);
        var_dump($response->body->resultObject->bizCode);
        exit;
        // $url = 'https://mobilecert.market.alicloudapi.com/mobile3Meta';
        // $data['mobile'] = $mobile;
        // $data['identifyNum'] = $idcard;
        // $data['userName'] = $person;
        // $header = ['Authorization' => 'APPCODE 08b451d6c29548b0a103147c131eb6e4'];
        // $http = new HttpRequest;
        // $result = $http->headers($header)->get($url . '?' . http_build_query($data));
        // $resultBody = json_decode($result->body(), true);
        // if ($resultBody['code'] != 200) {
        //     throw new ApiException('身份认证失败-' . $resultBody['message']);
        // }
        // $return['orderNo'] = $resultBody['requestId'];
        // if ($resultBody['data']['bizCode'] != 1) {
        //     switch ($resultBody['data']['subCode']) {
        //         case '301':
        //             throw new ApiException('身份认证失败-查无记录');
        //             break;
        //         case '201':
        //             throw new ApiException('身份认证失败-手机号和姓名不一致，手机号和证件号不一致');
        //             break;
        //         case '202':
        //             throw new ApiException('身份认证失败-⼿机号和姓名⼀致，⼿机号和证件号不⼀致');
        //             break;
        //         case '203':
        //             throw new ApiException('身份认证失败-⼿机号和证件号⼀致，⼿机号和姓名不⼀致');
        //             break;
        //         case '204':
        //             throw new ApiException('身份认证失败-其他不⼀致');
        //             break;
        //     }
        // }
        // return $return;
    }
    /**
     * id2MetaVerifyAutoRoute
     * @param Id2MetaVerifyRequest $request
     * @return Id2MetaVerifyResponse|null
     */
    public static function id2MetaVerifyAutoRoute(Id2MetaVerifyRequest $request): ?Id2MetaVerifyResponse
    {
        $endpoints = [
            "cloudauth.cn-shanghai.aliyuncs.com",
            "cloudauth.cn-beijing.aliyuncs.com"
        ];
        foreach ($endpoints as $endpoint) {
            try {
                $response = self::id2MetaVerify($endpoint, $request);
                if (Utils::equalNumber(500, $response->statusCode)) {
                    continue;
                }
                if (Utils::equalString("500", $response->body->code)) {
                    continue;
                }
                return $response;
            } catch (Exception $err) {
                var_dump($err->getCode());
                var_dump($err->getMessage());
            }
        }
        return null;
    }

    /**
     * id2MetaVerify
     * @param string $endpoint
     * @param Id2MetaVerifyRequest $request
     * @return Id2MetaVerifyResponse
     */
    public static function id2MetaVerify(string $endpoint, Id2MetaVerifyRequest $request): Id2MetaVerifyResponse
    {
        $client = self::createClient($endpoint);
        // 创建RuntimeObject实例并设置运行参数。
        $runtime = new RuntimeOptions([]);
        $runtime->readTimeout = 5000;
        $runtime->connectTimeout = 5000;
        return $client->id2MetaVerifyWithOptions($request, $runtime);
    }
    // 身份认证（三要素）
    // https://market.aliyun.com/products/57000002/cmapi029847.html?spm=5176.2020520132.101.4.21bf72187mY70T
    public static function mobile3Meta($mobile, $person, $idcard)
    {
        $url = 'https://mobilecert.market.alicloudapi.com/mobile3Meta';
        $data['mobile'] = $mobile;
        $data['identifyNum'] = $idcard;
        $data['userName'] = $person;
        $header = ['Authorization' => 'APPCODE 08b451d6c29548b0a103147c131eb6e4'];
        $http = new HttpRequest;
        $result = $http->headers($header)->get($url . '?' . http_build_query($data));
        $resultBody = json_decode($result->body(), true);
        if ($resultBody['code'] != 200) {
            throw new ApiException('身份认证失败-' . $resultBody['message']);
        }
        $return['orderNo'] = $resultBody['requestId'];
        if ($resultBody['data']['bizCode'] != 1) {
            switch ($resultBody['data']['subCode']) {
                case '301':
                    throw new ApiException('身份认证失败-查无记录');
                    break;
                case '201':
                    throw new ApiException('身份认证失败-手机号和姓名不一致，手机号和证件号不一致');
                    break;
                case '202':
                    throw new ApiException('身份认证失败-⼿机号和姓名⼀致，⼿机号和证件号不⼀致');
                    break;
                case '203':
                    throw new ApiException('身份认证失败-⼿机号和证件号⼀致，⼿机号和姓名不⼀致');
                    break;
                case '204':
                    throw new ApiException('身份认证失败-其他不⼀致');
                    break;
            }
        }
        return $return;
    }
    public static function pdf2png($pdf, $path)
    {
        $postData['url'] = 'https://plus.21ds.cn/storage/' . str_replace(UPLOAD_PATH, '', $pdf);
        $resultJava = javaApiRequest('ldp/contract/pdf_to_png', $postData);
        if ($resultJava['code'] == 200 && isset($resultJava['data']['pic'])) {
            return $resultJava['data']['pic'];
        }
        if (!extension_loaded('imagick')) {
            throw new ApiException('imagick 扩展未安装');
        }
        if (!file_exists($pdf)) {
            throw new ApiException('pdf 文件不存在');
        }
        $im = new \Imagick();
        $im->setResolution(120, 120); //设置分辨率 值越大分辨率越高
        $im->setCompressionQuality(100);
        $im->readImage($pdf);
        foreach ($im as $k => $v) {
            $v->setImageFormat('png');
            $fileName = $path . md5($k . time()) . '.png';
            if ($v->writeImage($fileName) == true) {
                $return[] = $fileName;
            }
        }
        return $return;
    }
    public static function pdf2jpg($pdf, $path)
    {
        if (!extension_loaded('imagick')) {
            throw new ApiException('imagick 扩展未安装');
        }
        if (!file_exists($pdf)) {
            throw new ApiException('pdf 文件不存在');
        }
        $im = new \Imagick();
        $im->setResolution(120, 120); //设置分辨率 值越大分辨率越高
        $im->setCompressionQuality(100);
        $im->readImage($pdf);
        foreach ($im as $k => $v) {
            $v->setImageFormat('jpeg');
            $fileName = $path . md5($k . time()) . '.jpg';
            if ($v->writeImage($fileName) == true) {
                $return[] = $fileName;
            }
        }
        return $return;
    }
    public static function validateLicenseNumber($number)
    {
        // 校验营业执照号
        $licenseRegex = '/^([0-9A-HJ-NPQRTUWXY]{15})$/';

        // 校验统一社会信用代码
        $creditRegex = '/^[0-9A-HJ-NPQRTUWXY]{18}$/';

        if (preg_match($licenseRegex, $number) || preg_match($creditRegex, $number)) {
            return true; // 号码格式正确
        } else {
            return false; // 号码格式不正确
        }
    }
    public static function validateIdCard($number)
    {
        $preg_card = '/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}[\dX]$/';
        if (!preg_match($preg_card, $number)) {
            return false;
        }
        return true;
    }
}
